Agent with custom HTTP Request

工作流概述

这是一个包含20个节点的复杂工作流,主要用于自动化处理各种任务。

工作流源代码

下载
{
  "id": "dsKnCFwysROIA4MT",
  "meta": {
    "instanceId": "03524270bab2c2dfd5b82778cd1355e56cdda3cf098bf2dfd865e18164c00485"
  },
  "name": "Agent with custom HTTP Request",
  "tags": [],
  "nodes": [
    {
      "id": "e7374976-f3c1-4f60-ae57-9eec65444216",
      "name": "On new manual Chat Message",
      "type": "@n8n/n8n-nodes-langchain.manualChatTrigger",
      "position": [
        763,
        676
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "97e84a23-9536-43cd-94e9-b8166be8ed32",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        983,
        896
      ],
      "parameters": {
        "model": "gpt-4-1106-preview",
        "options": {
          "timeout": 300000,
          "temperature": 0.7,
          "frequencyPenalty": 0.3
        }
      },
      "credentials": {
        "openAiApi": {
          "id": "wPFAzp4ZHdLLwvkK",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "63d98361-8978-4042-84e7-53a0e226f946",
      "name": "HTTP Request",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueRegularOutput",
      "position": [
        1360,
        1200
      ],
      "parameters": {
        "url": "={{ encodeURI($json.query.url) }}",
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          },
          "allowUnauthorizedCerts": true
        }
      },
      "typeVersion": 4.1,
      "alwaysOutputData": false
    },
    {
      "id": "17d4b5ae-f5d3-4793-8419-d3c879f7f50d",
      "name": "Exctract HTML Body",
      "type": "n8n-nodes-base.set",
      "position": [
        1780,
        1480
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "HTML",
              "stringValue": "={{ $json?.data.match(/<body[^>]*>([\s\S]*?)<\/body>/i)[1] }}"
            }
          ]
        },
        "include": "selected",
        "options": {},
        "includeFields": "HTML"
      },
      "typeVersion": 3.2
    },
    {
      "id": "36c38ee4-724c-4ba2-a59a-ac0bbc912e94",
      "name": "Is error?",
      "type": "n8n-nodes-base.if",
      "position": [
        1560,
        1200
      ],
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.hasOwnProperty('error') }}",
              "value2": true
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "4e4d97ce-14a9-4f4f-aa75-f218784d9ed9",
      "name": "Stringify error message",
      "type": "n8n-nodes-base.set",
      "position": [
        1780,
        980
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "page_content",
              "stringValue": "={{ $('QUERY_PARAMS').first()?.json?.query?.url == null ? \"INVALID action_input. This should be an HTTP query string like this: \\"?url=VALIDURL&method=SELECTEDMETHOD\\". Only a simple string value is accepted. JSON object as an action_input is NOT supported!\" : JSON.stringify($json.error) }}"
            }
          ]
        },
        "include": "selected",
        "options": {},
        "includeFields": "HTML"
      },
      "typeVersion": 3.2
    },
    {
      "id": "8452e5c4-aa29-4a02-9579-8d9da3727bcb",
      "name": "Execute Workflow Trigger",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "position": [
        760,
        1200
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "063220c2-fa4d-4d5e-9549-7712aaa72921",
      "name": "Remove extra tags",
      "type": "n8n-nodes-base.set",
      "position": [
        1980,
        1480
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "HTML",
              "stringValue": "={{ ($json.HTML || \"HTML BODY CONTENT FOR THIS SEARCH RESULT IS NOT AVAILABLE\").replace(/<script[^>]*>([\s\S]*?)<\/script>|<style[^>]*>([\s\S]*?)<\/style>|<noscript[^>]*>([\s\S]*?)<\/noscript>|<!--[\s\S]*?-->|<iframe[^>]*>([\s\S]*?)<\/iframe>|<object[^>]*>([\s\S]*?)<\/object>|<embed[^>]*>([\s\S]*?)<\/embed>|<video[^>]*>([\s\S]*?)<\/video>|<audio[^>]*>([\s\S]*?)<\/audio>|<svg[^>]*>([\s\S]*?)<\/svg>/ig, '')}}"
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "036511d7-a4be-4bbf-b4bc-47ddfabfe76f",
      "name": "Simplify output",
      "type": "n8n-nodes-base.set",
      "notes": "remove links and image URLs",
      "position": [
        2360,
        1380
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "HTML",
              "stringValue": "={{ $json.HTML.replace(/href\s*=\s*\"(.+?)\"/gi, 'href=\"NOURL\"').replace(/src\s*=\s*\"(.+?)\"/gi, 'src=\"NOIMG\"')}}"
            }
          ]
        },
        "options": {}
      },
      "notesInFlow": true,
      "typeVersion": 3.2
    },
    {
      "id": "5e2b5383-adcf-4de0-a406-4f5d631b5e8a",
      "name": "Simplify?",
      "type": "n8n-nodes-base.if",
      "position": [
        2180,
        1480
      ],
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $('CONFIG').first()?.json?.query?.method }}",
              "value2": "simplif",
              "operation": "contains"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "a0fc004a-ab0f-4b31-94df-50f5eee69c86",
      "name": "QUERY_PARAMS",
      "type": "n8n-nodes-base.set",
      "position": [
        960,
        1200
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "query",
              "type": "objectValue",
              "objectValue": "={{ $json.query.substring($json.query.indexOf('?') + 1).split('&').reduce((result, item) => (result[item.split('=')[0]] = decodeURIComponent(item.split('=')[1]), result), {}) }}"
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "3b6599d6-ce9a-4861-9b52-07156eb52539",
      "name": "CONFIG",
      "type": "n8n-nodes-base.set",
      "position": [
        1160,
        1200
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "query.maxlimit",
              "type": "numberValue",
              "numberValue": "={{ $json?.query?.maxlimit == null ? 70000 : Number($json?.query?.maxlimit) }}"
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "14f683be-76f6-4034-9a0e-d785738b135f",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        721,
        1134
      ],
      "parameters": {
        "width": 556.25,
        "height": 235.79999999999995,
        "content": "### Convert the query string into JSON, apply the limit for a page length"
      },
      "typeVersion": 1
    },
    {
      "id": "6deabcb7-a984-48ec-af2a-8c70b3a4e4bf",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1720,
        840
      ],
      "parameters": {
        "width": 491,
        "height": 285.7,
        "content": "## Send an error message:
1. If query param was incorrect, return the instruction. AI Agent should pick up on this and adapt the query on the next iteration.
2. If the query is OK and an error was during the HTTP Request, then send back the original error message."
      },
      "typeVersion": 1
    },
    {
      "id": "df1e8d00-0e18-44fa-8f94-8a53c27f7c88",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1720,
        1160
      ],
      "parameters": {
        "width": 1200,
        "height": 472.5,
        "content": "## Post-processing of the HTML page:
1. Keep only <BODY> content
2. Remove inline <SCRIPT> tag entirely, as well as: NOSCRIPT, IFRAME, OBJECT, EMBED, VIDEO, AUDIO, SVG, and HTML comments.
3. In case query parameter method=simplified, replace all page URLs (a href) and IMG (src) with NOURL / NOIMG - this may save up to 20% of the page length
4. Convert the remaining HTML to Markdown. This step further reduces the length of the page: long HTML tags and styles are eliminated, but the markdown syntax keeps some page structure. This gives much better results compared to just a blank text.
5. Finally, check the page length. If it's too long, send an \"ERROR: PAGE CONTENT TOO LONG\" instead of the actual page. Of course, you could split the page content in chunks, but sometimes long pages just don't have a needed content, so it makes little sense to burn tokens on them."
      },
      "typeVersion": 1
    },
    {
      "id": "6afe96a0-0fba-4ae1-ab8f-f7da56d420b1",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        720,
        540
      ],
      "parameters": {
        "width": 616.8597285067872,
        "height": 483.0226244343891,
        "content": "## Example ReAct AI Agent
1. Agent Prompt is default
2. Check the description of the HTTP_Request_Tool, it guides the agent to provide a query string with several parameters instead of a JSON object"
      },
      "typeVersion": 1
    },
    {
      "id": "d5ff2114-1e74-43cf-9f3c-744c241988db",
      "name": "ReAct AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        983,
        676
      ],
      "parameters": {
        "agent": "reActAgent",
        "options": {
          "prefix": "Answer the following questions as best you can. You have access to the following tools:",
          "suffix": "Begin!

	Question: {input}
	Thought:{agent_scratchpad}",
          "suffixChat": "Begin! Reminder to always use the exact characters `Final Answer` when responding.",
          "humanMessageTemplate": "{input}

{agent_scratchpad}"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "cc7aef4a-a1fb-4a69-a670-1f200f9e9541",
      "name": "Convert to Markdown",
      "type": "n8n-nodes-base.markdown",
      "position": [
        2540,
        1480
      ],
      "parameters": {
        "html": "={{ $json.HTML }}",
        "options": {},
        "destinationKey": "page_content"
      },
      "typeVersion": 1
    },
    {
      "id": "11806e8c-5fc4-4d9d-8144-179356993aa7",
      "name": "Send Page Content",
      "type": "n8n-nodes-base.set",
      "position": [
        2740,
        1480
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "page_content",
              "stringValue": "={{ $json.page_content.length < $('CONFIG').first()?.json?.query?.maxlimit ? $json.page_content : \"ERROR: PAGE CONTENT TOO LONG\" }}"
            },
            {
              "name": "page_length",
              "type": "numberValue",
              "numberValue": "={{ $json.page_content.length }}"
            }
          ]
        },
        "include": "selected",
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "a3a6b199-517b-4987-8281-d7997a32f54b",
      "name": "HTTP_Request_Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        1103,
        896
      ],
      "parameters": {
        "name": "HTTP_Request_Tool",
        "workflowId": "={{ $workflow.id }}",
        "description": "Call this tool to fetch a webpage content. The input should be a stringified HTTP query parameter like this: \"?url=VALIDURL&method=SELECTEDMETHOD\". \"url\" parameter should contain the valid URL string. \"method\" key can be either \"full\" or \"simplified\". method=full will fetch the whole webpage content in the Markdown format, including page links and image links. method=simplified will return the Markdown content of the page but remove urls and image links from the page content for simplicity. Before calling this tool, think strategically which \"method\" to call. Best of all to use method=simplified. However, if you anticipate that the page request is not final or if you need to extract links from the page, pick method=full.",
        "responsePropertyName": "page_content"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "9db853c5-3658-47c1-b98a-5858b1c184ec",
  "connections": {
    "CONFIG": {
      "main": [
        [
          {
            "node": "HTTP Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is error?": {
      "main": [
        [
          {
            "node": "Stringify error message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Exctract HTML Body",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simplify?": {
      "main": [
        [
          {
            "node": "Simplify output",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Convert to Markdown",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request": {
      "main": [
        [
          {
            "node": "Is error?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "QUERY_PARAMS": {
      "main": [
        [
          {
            "node": "CONFIG",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simplify output": {
      "main": [
        [
          {
            "node": "Convert to Markdown",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP_Request_Tool": {
      "ai_tool": [
        [
          {
            "node": "ReAct AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "ReAct AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Remove extra tags": {
      "main": [
        [
          {
            "node": "Simplify?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Exctract HTML Body": {
      "main": [
        [
          {
            "node": "Remove extra tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert to Markdown": {
      "main": [
        [
          {
            "node": "Send Page Content",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute Workflow Trigger": {
      "main": [
        [
          {
            "node": "QUERY_PARAMS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "On new manual Chat Message": {
      "main": [
        [
          {
            "node": "ReAct AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

功能特点

  • 自动检测新邮件
  • AI智能内容分析
  • 自定义分类规则
  • 批量处理能力
  • 详细的处理日志

技术分析

节点类型及作用

  • @N8N/N8N Nodes Langchain.Manualchattrigger
  • @N8N/N8N Nodes Langchain.Lmchatopenai
  • Httprequest
  • Set
  • If

复杂度评估

配置难度:
★★★★☆
维护难度:
★★☆☆☆
扩展性:
★★★★☆

实施指南

前置条件

  • 有效的Gmail账户
  • n8n平台访问权限
  • Google API凭证
  • AI分类服务订阅

配置步骤

  1. 在n8n中导入工作流JSON文件
  2. 配置Gmail节点的认证信息
  3. 设置AI分类器的API密钥
  4. 自定义分类规则和标签映射
  5. 测试工作流执行
  6. 配置定时触发器(可选)

关键参数

参数名称 默认值 说明
maxEmails 50 单次处理的最大邮件数量
confidenceThreshold 0.8 分类置信度阈值
autoLabel true 是否自动添加标签

最佳实践

优化建议

  • 定期更新AI分类模型以提高准确性
  • 根据邮件量调整处理批次大小
  • 设置合理的分类置信度阈值
  • 定期清理过期的分类规则

安全注意事项

  • 妥善保管API密钥和认证信息
  • 限制工作流的访问权限
  • 定期审查处理日志
  • 启用双因素认证保护Gmail账户

性能优化

  • 使用增量处理减少重复工作
  • 缓存频繁访问的数据
  • 并行处理多个邮件分类任务
  • 监控系统资源使用情况

故障排除

常见问题

邮件未被正确分类

检查AI分类器的置信度阈值设置,适当降低阈值或更新训练数据。

Gmail认证失败

确认Google API凭证有效且具有正确的权限范围,重新进行OAuth授权。

调试技巧

  • 启用详细日志记录查看每个步骤的执行情况
  • 使用测试邮件验证分类逻辑
  • 检查网络连接和API服务状态
  • 逐步执行工作流定位问题节点

错误处理

工作流包含以下错误处理机制:

  • 网络超时自动重试(最多3次)
  • API错误记录和告警
  • 处理失败邮件的隔离机制
  • 异常情况下的回滚操作